import { useUserStoreHook } from '@/stores/modules/user'

const useUserStore = useUserStoreHook()

export default {
	common: {
		// https://partner-api.test.zhubei.cn/api/wechat_mini/wx_mini_program_auth
		baseUrl: 'https://partner-api.test.zhubei.cn/api',
		header: {
			'Authorization': '',
			'content-type': 'application/x-www-form-urlencoded',
		},
		timeout: 60000,
		method: 'GET',
		dataType: 'json',
		data: {},
		checkTok: true
	},
	request(options={}) {
		options.url = this.common.baseUrl + options.url;
		options.data = options.data || this.common.data;
		options.header = options.header || this.common.header;
		options.dataType = options.dataType || this.common.dataType;
		options.method = options.method || this.common.method;
		options.timeout = options.timeout || this.common.timeout;
		options.checkTok = options.checkTok || this.common.checkTok;

		
		if(options.header.token) {
			delete options.header.token
			options.header['Authorization'] = useUserStore.userinfo.token
			if(options.header['Authorization'] === '') {
				uni.navigateTo({
					url: '/pages/login/login'
				})
				return new Promise((resolve, reject) => {
					resolve({
						code: 400,
						msg: '请求登录',
						data: {}
					})
				})
			}
		}
		uni.showLoading();
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				success: (res)=>{
					if(res.statusCode !== 200) { 
						reject();
						return;
					}
					uni.hideLoading();
					resolve(res.data);
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err);
				}
			})
		})
	},
	uploadFile(options = {}) {
		options.url = this.common.baseUrl + options.url;
		options.method = options.method || this.common.method;
		options.header = options.header || this.common.header;
		options.filePath = options.filePath || '';
		options.name = options.name || 'file';
		options.formData = options.data || {}
		delete options.data
		
		if(options.header.token) {
			delete options.header.token
			options.header['Authorization'] = useUserStore.userinfo.token
			if(options.header['Authorization'] === '') {
				uni.navigateTo({
					url: '/pages/login/login'
				})
				return new Promise((resolve, reject) => {
					resolve({
						code: 400,
						msg: '请求登录',
						data: {}
					})
				})
			}
		}
		uni.showLoading();
		return new Promise((resolve, reject) => {
			uni.uploadFile({
		   ...options,
				success: (uploadFileRes) => {
					if(uploadFileRes.statusCode !== 200) {
						reject();
						return;
					}
					uni.hideLoading();
					resolve(JSON.parse(uploadFileRes.data))
				},
				file: (err) => {
					reject(err)
				}
			});
		})
	}
}
